package cn.wildfire.chat.kit.group;

import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.List;

import cn.wildfire.chat.app.extendsion.ui.SmoothToggleAndSlideAnimationForUI;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.contact.model.UIUserInfo;
import cn.wildfire.chat.kit.contact.pick.PickUserViewModel;
import cn.wildfire.chat.kit.group.manage.OnPickUserStatusChangeListener;
import cn.wildfire.chat.kit.third.utils.UIUtils;
import cn.wildfirechat.model.GroupInfo;

public class AddGroupMemberActivity extends WfcBaseActivity {

    private MenuItem menuItem;

    private GroupInfo groupInfo;
    public static final int RESULT_ADD_SUCCESS = 2;
    public static final int RESULT_ADD_FAIL = 3;

    private PickUserViewModel pickUserViewModel;
    private GroupViewModel groupViewModel;
    private Observer<UIUserInfo> contactCheckStatusUpdateLiveDataObserver = new Observer<UIUserInfo>() {
        @Override
        public void onChanged(@Nullable UIUserInfo userInfo) {
            List<UIUserInfo> list = pickUserViewModel.getCheckedUsers();
            if (list == null || list.isEmpty()) {
                menuItem.setTitle("确定");
                menuItem.setEnabled(false);
            } else {
                menuItem.setTitle("确定(" + list.size() + ")");
                menuItem.setEnabled(true);
            }
        }
    };

    @Override
    protected int contentLayout() {
        return R.layout.fragment_container_activity;
    }

    @Override
    protected void afterViews() {
        groupInfo = getIntent().getParcelableExtra("groupInfo");
        if (groupInfo == null) {
            finish();
            return;
        }

        pickUserViewModel = ViewModelProviders.of(this).get(PickUserViewModel.class);
        pickUserViewModel.userCheckStatusUpdateLiveData().observeForever(contactCheckStatusUpdateLiveDataObserver);
        groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
        addGroupMemberFragment = AddGroupMemberFragment.newInstance(groupInfo);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.containerFrameLayout, addGroupMemberFragment)
                .commit();
        addGroupMemberFragment.setOnPickUserStatusChangeListener(onPickUserStatusChangeListener);
    }

    /**
     * 用于选择用户回调状态改变右上角显示文字及对应操作类型
     */
    private OnPickUserStatusChangeListener onPickUserStatusChangeListener = new OnPickUserStatusChangeListener() {
        @Override
        public void showSearchResult(boolean searching) {
            getRightTxtView().setText(searching ? getString(R.string.done_title) : getString(R.string.confirm));
        }
    };

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        setReplaceTitle(getTitle().toString(), -1);
        setSearchLayoutVisibility(false);
        setTextThenBinClickForRightTextView(View.VISIBLE, getString(R.string.confirm), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = getRightTxtView().getText().toString();
                if (text.equals(getString(R.string.confirm))) {
                    addMember();
                } else {
                    // 隐藏搜索内容
                    addGroupMemberFragment.hideSearchContactFragment();
                }
            }
        });
    }

    @Override
    protected int menu() {
        return R.menu.group_add_member;
    }

    @Override
    protected void afterMenus(Menu menu) {
        menuItem = menu.findItem(R2.id.add);
        super.afterMenus(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R2.id.add) {
            addMember();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pickUserViewModel.userCheckStatusUpdateLiveData().removeObserver(contactCheckStatusUpdateLiveDataObserver);
    }


    void addMember() {
        List<UIUserInfo> checkedUsers = pickUserViewModel.getCheckedUsers();
        if (checkedUsers == null || checkedUsers.size() == 0) {
            ToastTip.tip("未选中可增加的新成员!");
            return;
        }
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("添加中...")
                .progress(true, 100)
                .cancelable(false)
                .build();
        dialog.show();
        if (checkedUsers != null && !checkedUsers.isEmpty()) {
            ArrayList<String> checkedIds = new ArrayList<>(checkedUsers.size());
            for (UIUserInfo user : checkedUsers) {
                checkedIds.add(user.getUserInfo().uid);
            }
            groupViewModel.addGroupMember(groupInfo, checkedIds).observe(this, result -> {
                dialog.dismiss();
                Intent intent = new Intent();
                if (result) {
                    intent.putStringArrayListExtra("memberIds", checkedIds);
                    setResult(RESULT_ADD_SUCCESS, intent);
                    UIUtils.showToast(UIUtils.getString(R.string.add_member_success));
                } else {
                    UIUtils.showToast(UIUtils.getString(R.string.add_member_fail));
                    setResult(RESULT_ADD_FAIL);
                }
                finish();
            });
        }
    }

    /**
     * modify by HEKE , 2019/9/4 18:55 TODO 测试滑动隐藏或显示搜索栏 HEKE_SEARCHLAYOUT_ADD
     */
    protected AddGroupMemberFragment addGroupMemberFragment;
    protected SmoothToggleAndSlideAnimationForUI smoothToggleAndSlideAnimationForUI;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (smoothToggleAndSlideAnimationForUI == null) {
                smoothToggleAndSlideAnimationForUI = new SmoothToggleAndSlideAnimationForUI(this, SmoothToggleAndSlideAnimationForUI.FLAG_GROUP_ADD_REMOVE);
                smoothToggleAndSlideAnimationForUI.setToggleView(addGroupMemberFragment.getSearchLayout());
                smoothToggleAndSlideAnimationForUI.setSlideView(addGroupMemberFragment.getUsersRecyclerView(), 0);
            }
            smoothToggleAndSlideAnimationForUI.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.dispatchTouchEvent(ev);
    }

}
